#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询生成器模块

生成自然语言查询语句的智能生成器
"""

import logging
from llama_index.core import PromptTemplate
from .data_structures import AnalysisContext
from .enums import QueryType
from biz.core.ai.prompts import QUERY_GENERATION_PROMPT

logger = logging.getLogger(__name__)


class EnhancedQueryGenerator:
    """增强版查询生成器 - 根据分析上下文生成智能查询"""
    
    def __init__(self, llm):
        self.llm = llm
        self.query_generation_prompt = PromptTemplate(QUERY_GENERATION_PROMPT)
    
    async def generate_query(self, query_type: QueryType, analysis_context: AnalysisContext) -> str:
        try:
            expected_insights = "; ".join(analysis_context.expected_insights) if analysis_context.expected_insights else "无"
            historical_issue = self._summarize_historical_issue(analysis_context)
            purpose_map = {
                QueryType.DEVICE_BASIC_INFO: "设备基本信息",
                QueryType.FAULT_RECORDS: "故障记录",
                QueryType.DEVICE_EXISTENCE: "设备存在性检查",
                QueryType.STATISTICS_RECORDS: "统计记录",
            }
            check_purpose = purpose_map.get(query_type, "其他")
            prompt = self.query_generation_prompt.format(
                check_purpose=check_purpose,
                user_input=analysis_context.user_input,
                device_ids=", ".join(analysis_context.device_ids) if analysis_context.device_ids else "无",
                round_number=analysis_context.current_round,
                max_rounds=analysis_context.max_rounds,
                expected_insights=expected_insights,
                historical_issue=historical_issue,
            )
            
            response = await self.llm.acomplete(prompt)
            query = str(response).strip()
            
            logger.info(f"生成的{query_type.value}查询: {query}")
            return query
            
        except Exception as e:
            logger.error(f"查询生成失败: {str(e)}")
            # 返回默认查询
            device_str = ", ".join(analysis_context.device_ids) if analysis_context.device_ids else "相关设备"
            return f"查询设备编号为 {device_str} 的基本信息和在线状态"

    def _summarize_historical_issue(self, analysis_context: AnalysisContext) -> str:
        """生成历史问题摘要（仅返回历史查询的 query_text 合并）。

        - 收集 previous_results 中的 query_text，合并为一条简短文本返回；
        - 为空时返回 "无"；
        - 为保持精炼，仅保留最近3条，并限制总长度。
        """
        results = analysis_context.previous_results or []
        if not results:
            return "无"

        texts = []
        for r in results:
            qt = (getattr(r, "query_text", None) or "").strip()
            if qt:
                texts.append(qt)

        if not texts:
            return "无"

        concise = texts[-3:]
        joined = "；".join(concise)
        return joined
